import axios from 'axios';
import { history } from 'umi';
import SecurityService from './pages/login/service';

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/service';
}

const instance = axios.create({
  headers: {
    'x-requested-with': 'XMLHttpRequest',
    "content-type": "application/json;charset=UTF-8"
  },
});

instance.interceptors.request.use((request) => {
  const user: any = SecurityService.getSecurity().token;
  if (user) {
    request.headers = {
      ...request.headers,
      Authorization:'Bearer '+ user,
    };
  }
  return request;
});

instance.interceptors.response.use(
  (response) => {
    if (response) {
      return response.data;
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        history.replace('/401');
      } else if (error.response.status === 403) {
        history.replace('/403');
      } else if (error.response.status === 404) {
        history.replace('/404');
      } else {
        history.replace('/500');
      }
      return Promise.reject(error.response);
    }
    history.replace('/500');
    return Promise.reject(error);
  },
);

export default instance;
